//
//  OASendMessageDetailController.m
//  OASystem
//
//  Created by zhoupengfei on 15/4/14.
//  Copyright (c) 2015年 zpf. All rights reserved.
//
#import "OANewEmailController.h"
#import "OASendMessageDetailController.h"
#import "OASendDetailCell.h"
#import "OASendDetailModel.h"
#import "GDataDefines.h"
#import "OAAttachmentsModel.h"
#import <QuickLook/QuickLook.h>
@interface OASendMessageDetailController ()<UITableViewDataSource,UITableViewDelegate,QLPreviewControllerDataSource,QLPreviewControllerDelegate,UIActionSheetDelegate>
@property(nonatomic,strong)OASendDetailModel * detailModel;
@property(nonatomic,strong)NSMutableArray * attachmentArray;
@property(nonatomic,strong)NSString * attacmentURL;

@end

@implementation OASendMessageDetailController

-(NSMutableArray*)attachmentArray{
    if (_attachmentArray ==nil) {
        _attachmentArray = [NSMutableArray array];
    }
    return _attachmentArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.hidden = YES;
    self.view.backgroundColor = [UIColor colorWithHexString:@"f5f5f5"];
        self.tableView.bounces = NO;
if ([_type isEqualToString:@"kszf"]) {
    _url = KexchksmailURL;
      UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"邮件管理"style:UIBarButtonItemStylePlain target:self action:@selector(guanli)];

                         self.navigationItem.rightBarButtonItem = item1;
//    UIActionSheet *actionSheet = [[UIActionSheet alloc]
//                                  initWithTitle:@" 邮 件 管 理" delegate:self cancelButtonTitle:@"取 消" destructiveButtonTitle:nil otherButtonTitles:@"回 复",@"转 发" ,nil];
//    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
//    [actionSheet showInView:self.view];
}else if ([_type isEqualToString:@"ks"]||[_type isEqualToString:@"kscg"]){

    _url = KexchksmailURL;

}
else{

_url = KexchmailURL;
}
    [self loadData];
    if ([_type isEqualToString:@"grcg"]||[_type isEqualToString:@"kscg"]){
       UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"编辑"style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];

                         self.navigationItem.rightBarButtonItem = item1;
    
    }
if ([_type isEqualToString:@"zf"]) {
//      UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"转发"style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];
//
//                         self.navigationItem.rightBarButtonItem = item1;
        UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"邮件管理"style:UIBarButtonItemStylePlain target:self action:@selector(guanli)];

                         self.navigationItem.rightBarButtonItem = item1;
}
if ([_types isEqualToString:@"fs"]) {
 UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"未读名单"style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction1)];
 UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithTitle:@"已读名单"style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction2)];
 UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithTitle:@"转发"style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];

[self.navigationItem setRightBarButtonItems:@[item1,item2,item3]];
//[self requestdata];
}if ([_types isEqualToString:@"ksfs"]) {
 UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"未读名单"style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction1)];
 UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithTitle:@"已读名单"style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction2)];
 UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithTitle:@"转发"style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];

[self.navigationItem setRightBarButtonItems:@[item1,item2,item3]];
//[self requestdata];
}
}
- (void)guanli{

  UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:@" 邮 件 管 理" delegate:self cancelButtonTitle:@"取 消" destructiveButtonTitle:nil otherButtonTitles:@"回 复",@"转 发" ,nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];

}
- (void)requestdata{
NSString *method= nil;
NSString *url= nil;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
if([_type isEqualToString:@"ks"]||[_type isEqualToString:@"kscg"]){
method = @"exchksmail";
url = @"unreadlist";

}


else{
method = @"exchmail";
url = @"unreadlist";

}
[HttpTools requestWithURL:url arrays:@[@{@"unid":_fileId},@{@"sName":userId}] method:method success:^(id JSON) {
    NSLog(@"%@",JSON);

} failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];



}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    OANewEmailController * newEmailVC = (OANewEmailController*)[storyBoard instantiateViewControllerWithIdentifier:@"NewEmailVCID"];
     newEmailVC.newtype   = _type;
    newEmailVC.types = _type;
    newEmailVC.type = Reply;
    newEmailVC.uid =_fileId;
        newEmailVC.SenddetailModel = _detailModel;
        newEmailVC.attachmentArray = _attachmentArray;                        newEmailVC.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:newEmailVC animated:YES];
    
}else if (buttonIndex == 1){
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    OANewEmailController * newEmailVC = (OANewEmailController*)[storyBoard instantiateViewControllerWithIdentifier:@"NewEmailVCID"];
     newEmailVC.newtype   = _type;
    newEmailVC.types = _type;
    newEmailVC.type = Retweet;
    newEmailVC.uid =_fileId;
        newEmailVC.SenddetailModel = _detailModel;
        newEmailVC.attachmentArray = _attachmentArray;                        newEmailVC.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:newEmailVC animated:YES];
    
}
   
}




- (void)rightButtonAction1{
 
 NSString *method= nil;
NSString *url= nil;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
if([_type isEqualToString:@"ks"]){
url = @"exchksmail";
method = @"unreadlist";

}else{
url = @"exchmail";
method = @"unreadlist";

}

[HttpTools requestWithURL:url arrays:@[@{@"unid":_fileId},@{@"sName":userId}] method:method success:^(id JSON) {
    NSLog(@"%@",JSON);
NSArray *array = JSON[@"data"];
NSMutableArray *array1 = [NSMutableArray array];

if (array) {

 for (NSDictionary *dic in array) {
[array1 addObject:dic[@"name"]];
}
}
NSString *string = [array1 componentsJoinedByString:@","];
 UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"未读名单", nil) message:string preferredStyle:UIAlertControllerStyleAlert];
             UIAlertAction *action = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {


            }];

            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
} failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];


    
                  }
 - (void)rightButtonAction2{
 
 NSString *method= nil;
NSString *url= nil;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
if([_type isEqualToString:@"ks"]){
url = @"exchksmail";
method = @"readlist";

}else{
url = @"exchmail";
method = @"readlist";

}

[HttpTools requestWithURL:url arrays:@[@{@"unid":_fileId},@{@"sName":userId}] method:method success:^(id JSON) {
    NSLog(@"%@",JSON);
NSArray *array = JSON[@"data"];
NSMutableArray *array1 = [NSMutableArray array];

if (array) {

 for (NSDictionary *dic in array) {
[array1 addObject:dic[@"name"]];
}
}
NSString *string = [array1 componentsJoinedByString:@","];
 UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"已读名单", nil) message:string preferredStyle:UIAlertControllerStyleAlert];
             UIAlertAction *action = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {


            }];

            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
} failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];


     
                  }
- (void)rightButtonAction{
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    OANewEmailController * newEmailVC = (OANewEmailController*)[storyBoard instantiateViewControllerWithIdentifier:@"NewEmailVCID"];
     newEmailVC.newtype   = _type;
    newEmailVC.types = _type;
    newEmailVC.type = Retweet;
    newEmailVC.uid =_fileId;
        newEmailVC.SenddetailModel = _detailModel;
        newEmailVC.attachmentArray = _attachmentArray;                        newEmailVC.hidesBottomBarWhenPushed = YES;

    [self.navigationController pushViewController:newEmailVC animated:YES];
    
}
#pragma mark 加载网络数据
-(void)loadData{
//KContentMailMethod
if ([_type isEqualToString:@"grcg"]) {
    _url = @"exchmail";
    _method = @"contentdraftMail";
}else if ([_type isEqualToString:@"kscg"]){
    _url = @"exchksmail";
    _method = @"contentdraftMail";
}
else{
_method =KContentMailMethod;
}
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"unId":self.fileId},@{@"userId":userId}];
    [HttpTools postWithURL:_url arrays:array method:_method success:^(id JSON) {
    NSLog(@"%@",JSON);
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        self.tableView.hidden = NO;
        self.detailModel = [self getDetailModel:JSON];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
    
}

-(OASendDetailModel*)getDetailModel:(id)json{
    NSData * data = [json dataUsingEncoding:NSUTF8StringEncoding];
    GDataXMLDocument *xmlDocument = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点
    GDataXMLElement *rootElement = [xmlDocument rootElement];
    //获取根节点下的节点
    NSArray *rootData= [rootElement elementsForName:@"数据"];
    OASendDetailModel * model = [[OASendDetailModel alloc]init];
    for (GDataXMLElement *subElement in rootData) {
        NSArray *tempData = [subElement elementsForName:@"数据要素"];
        for (GDataXMLElement *data in tempData) {
            GDataXMLElement * fileNumElement = [[data elementsForName:@"SendTo"] objectAtIndex:0];
            model.sendTo = [fileNumElement stringValue];
            
            GDataXMLElement * dateElement = [[data elementsForName:@"From"] objectAtIndex:0];
            model.sourceFrom = [dateElement stringValue];
            
            GDataXMLElement * OrigUnitOrganElement = [[data elementsForName:@"Subject"] objectAtIndex:0];
            model.title = [OrigUnitOrganElement stringValue];
            
             GDataXMLElement * OrigUnitOrganElement2 = [[data elementsForName:@"sendFrom"] objectAtIndex:0];
            model.sendfrom = [OrigUnitOrganElement2 stringValue];
            
             GDataXMLElement * moreOrganElement = [[data elementsForName:@"more"] objectAtIndex:0];
            model.more = [moreOrganElement stringValue];
            GDataXMLElement * GwNumElement = [[data elementsForName:@"body"] objectAtIndex:0];
            model.content =  [[GwNumElement stringValue] stringByReplacingOccurrencesOfString:@"&#xd;" withString:@""];
        }
    }
    
    for (GDataXMLElement * element in rootData) {
        NSArray *array = [element elementsForName:@"附件"];
        for (GDataXMLElement * data in array) {
            OAAttachmentsModel * attachModel = [[OAAttachmentsModel alloc]init];
            GDataXMLElement * nameElement = [[data elementsForName:@"名称"] objectAtIndex:0];
            NSString *  name = [nameElement stringValue];
            attachModel.attachmentsTitle = name;
            
            GDataXMLElement * contentElement = [[data elementsForName:@"内容"] objectAtIndex:0];
            NSString *  content = [contentElement stringValue];
            attachModel.attachmentsURL = content;
//            && attachModel.attachmentsURL.length !=0
            if (attachModel.attachmentsTitle.length !=0 ) {
                                        [self.attachmentArray addObject:attachModel];

            }

        }
    }
    
    return model;
    
}

#pragma mark UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    switch (section) {
        case 0:
            return 4;
            break;
        case 1:
            return self.attachmentArray.count;
        default:
            return 1;
            break;
    }
}


#pragma mark UITbableViewCell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
    
    
    if (indexPath.row==1) {
        static NSString * cellIdentifier0 = @"cellId0";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier0];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
              UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(8, 0,50, 44)];
  label.textColor = [UIColor blackColor];
label.text = @"收件人:";
    label.font = [UIFont systemFontOfSize:14];
    [cell.contentView addSubview:label];
        CGFloat height = 44;

                height = [OAToolBox sizebyText:self.detailModel.sourceFrom font:13 minsWidth:60]+ 35;

             _label2 = [[UILabel alloc]initWithFrame:CGRectMake(label.right+4, 0,KScreenWidth-50-4-10-8-60, 44)];
  _label2.textColor = [UIColor colorWithHexString:@"6F7179"];
_label2.text = self.detailModel.sourceFrom;
    _label2.font = [UIFont systemFontOfSize:13];
    [cell.contentView addSubview:_label2];
//    6F7179
_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button setImage:[UIImage imageNamed:@"add_pic"] forState:UIControlStateNormal];
_button.frame = CGRectMake(KScreenWidth-50, 7, 30, 30);
[_button addTarget:self action:@selector(action) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:_button];
//        _button.hidden = YES;

        }
//         NSArray  *array = [self.detailModel.sourceFrom componentsSeparatedByString:@","];
//         if(array.count>3){
//        _button.hidden = NO;
//         }
       _label2.text = self.detailModel.sourceFrom;

        return cell;
    }else{
        OASendDetailCell * cell = [OASendDetailCell cellWihtTableView:tableView];
        cell.detailModel = self.detailModel;
        cell.indexPath = indexPath;
        return cell;
        }
    }else{
        static NSString * cellIdentifier = @"cellId";
        UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        }
        OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
        cell.textLabel.text = model.attachmentsTitle;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.numberOfLines = 0;
        cell.textLabel.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
        return cell;
    }
    
}
- (void)action{
                              UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"收件人", nil) message:self.detailModel.more preferredStyle:UIAlertControllerStyleAlert];
             UIAlertAction *action = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {


            }];

            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
                  }
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = 44;
    if (indexPath.section ==0) {
        if (indexPath.row ==0) {
            height = [OAToolBox sizebyText:self.detailModel.sendTo font:13 minsWidth:60]+ 35;
            
        }else if (indexPath.row ==1){
//            height = [OAToolBox sizebyText:self.detailModel.sourceFrom font:13 minsWidth:60]+ 35;
            height = 44;
            
        }else if (indexPath.row ==2){
            
            height = [OAToolBox sizebyText:self.detailModel.title font:13 minsWidth:60]+ 35;
            
            
        }else if (indexPath.row ==3){
            
            height = [OAToolBox sizebyText:self.detailModel.content font:13 minsWidth:60]+ 35;
            
            
        }
    }else if (indexPath.section == 1){
        OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
        height = [OAToolBox sizebyText:model.attachmentsTitle font:13 minsWidth:20]+ 35;
    }
    return height;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        return 21;
    }
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 1) {
        UIView * bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 21)];
        UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(10, 0, KScreenWidth, 21)];
        label.text = @"附件";
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRed:85/255.0 green:85/255.0  blue:85/255.0 alpha:1.0];
        if (self.attachmentArray.count) {
            label.hidden = NO;
        }else{
            label.hidden = YES;
        }
        [bgView addSubview:label];
        return bgView;
    }
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1) { //下载附件 查看附件信息
        OAAttachmentsModel * model = self.attachmentArray[indexPath.row];
//        [self openFileURL:model.attachmentsURL];
 fujianwebViewController *vc = [[fujianwebViewController alloc]init];
        vc.url = model.attachmentsURL;
        if(model.attachmentsURL.length>0){
        [self.navigationController pushViewController:vc animated:YES];
        }else{
        
        [self.view makeToast:@"大附件请在电脑上下载或查看"];
        }
    }
    
}

-(void)openFileURL:(NSString*)url{
// ios 9新写法
    NSString * stringurl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    //NSString * stringurl = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    self.attacmentURL =  [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[url lastPathComponent]]; //附件路径
    if ([self isExtistFilePathWithFileName:[[NSURL URLWithString:stringurl] lastPathComponent]]) { //已经存在附件
        QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
        previewoCntroller.delegate=self;
        previewoCntroller.dataSource=self;
        previewoCntroller.navigationItem.rightBarButtonItem=nil;
        
        [self.navigationController pushViewController: previewoCntroller animated:YES];
        
    }else{
        
        MBProgressHUD * hud  =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"下载中...";
        NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:stringurl]];
        [self.webView loadRequest:request];
    }
    
}

#pragma mark PreviewDataSource
//第一个方法是设定一组文档浏览的个数，会影响到在文档预览中的上/下一页。
-(NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return 1;
}
//第二个方法是指定文档预览的文件路径
-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    
    return [NSURL fileURLWithPath:self.attacmentURL];
}

-(BOOL)isExtistFilePathWithFileName:(NSString*)fileName{
    NSString * file = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString * filePath = [file stringByAppendingPathComponent:fileName];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath] && fileName.length != 0) {
        return YES;
    }else{
        return NO;
    }
    
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSURL * requestedURL = [request URL];
    NSData * fileData = [[NSData alloc] initWithContentsOfURL:requestedURL];
    NSString * filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    [fileData writeToFile:[filePath stringByAppendingPathComponent:[requestedURL lastPathComponent]] atomically:YES];
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    QLPreviewController *previewoCntroller = [[QLPreviewController alloc] init] ;
    previewoCntroller.delegate=self;
    previewoCntroller.dataSource=self;
    [self.navigationController pushViewController: previewoCntroller animated:YES];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}

@end
